import { AREA_MOVE_DURATION, BLOCK_ELIMINATE_LIMIT, CUSTOM_EVENT_NAME, SCENES_NAME } from "../Common/Constant";
import { GameData, GetAccountInfo} from "../Common/GameData";
import { JsbTileTrileTileCallMgr } from "../Common/JsbMgr";
import LanguagetileTile, { Country } from "../Common/Language";
import CatcherController from "../Game/CatcherController";
import GamePlayController from "../Game/GamePlayController";
import MoneyFlySky from "../Game/MoneyFlySky";
import ProgressController from "../Game/ProgressController";
import RedbagFlySky from "../Game/RedbagFlySky";
import SingleBlockController from "../Game/SingleBlockController";
import TopAreaTs from "../Game/TopAreaTs";
import getEventEmiter from "../Libraries/EventEmitter";
import GamingSystem from "../System/GamingSystem";
import SceneManagerSystem from "../System/SceneManagerSystem";
import ArchiveSystem from "../System/ArchiveSystem";
import Archive from "../Common/Archive";
import GameTileStaticData from "../GameStaticData";
import CCLog from "../CCLog";

import GameTileStaticJsonData from "../GameStaticJsonData";
import LocalKey from "../LocalKey";
import ProgressPassNum from "../Game/ProgressPassNum";
import { wabaoEmit } from "../panels/wabao/wabaoMain";
const { ccclass, property } = cc._decorator;

@ccclass
export default class GameSceneController extends cc.Component {
    public static I: GameSceneController;

    @property(cc.Node)
    UGuider1:cc.Node = null;
    @property(cc.Node)
    UGuiderToDraw:cc.Node = null;
    @property(cc.Node)
    NewPhoneNode:cc.Node = null;
    @property(cc.Node)
    moneyNode:cc.Node = null;
    @property(cc.Node)
    iphoneBtnNode:cc.Node = null;
    @property(cc.Node)
    UICashTipNode:cc.Node = null;

    @property(cc.Sprite)
    gameBg:cc.Sprite = null;

    @property(cc.Label)
    labelTip:cc.Label = null;
    @property(cc.RichText)
    startTip:cc.RichText = null;
    
    @property(cc.Node)
    winMoneyNode: cc.Node = null;  //获奖人员node

    public onLoad() {
        GameSceneController.I = this;
        getEventEmiter().on(CUSTOM_EVENT_NAME.onGameStart,this.onGameStart.bind(this),this.node);
        getEventEmiter().on("updateNewPhoneIcon",this.updateNewPhoneIcon.bind(this),this.node);
        getEventEmiter().on("changeBg",this.changeBg.bind(this),this.node);
        this.updateNewPhoneIcon();
        this.winMoneyNode.active = false;
        this.labelTip.string = LanguagetileTile.getWord("topcashTip")
        this.startTip.string = LanguagetileTile.getWord("startTipCenter",GameTileStaticJsonData.tixianParm.sl)
        //this.executeEvery50Seconds();
    }

    public start() {
        let bgId = GameTileStaticJsonData.getLocalNormalByKey(LocalKey.localBg)
        this.changeBg(bgId)
        
        
        if (GameTileStaticJsonData.getLocalNormalByKey(LocalKey.localCashStartTip) == 0&&GameTileStaticData.isShenHeModel == false) {
            this.UICashTipNode.active = true
        }else{
            this.UICashTipNode.active = false
            this.startGame();
        }
    }
    public changeBg (id)
    {
        if (id>=19) {
            id = 0
        }
        let url = "jsResourc/game2/game/bgBig/bg_" + (id+1);
        GameTileStaticJsonData.saveLocalNormalByKey(LocalKey.localBg,id)
        cc.resources.load(url, cc.SpriteFrame, function (err, spriteFrame:cc.SpriteFrame) {
            if(GameSceneController.I)
            {
                GameSceneController.I.gameBg.spriteFrame = spriteFrame;
            }
            
        });

    
      
    }
    public controleShenHeNode(isShow:boolean = false){
        this.moneyNode.active = isShow
        this.iphoneBtnNode.active = isShow
    }
    onClickUICashTip(){
        this.UICashTipNode.active = false
        this.startGame();
        GameTileStaticJsonData.saveLocalNormalByKey(LocalKey.localCashStartTip,1)
        let jsonStr = {event:"startclick",loglevel:2}
        JsbTileTrileTileCallMgr.handler("buryPoint","(Ljava/lang/String;)V",JSON.stringify(jsonStr))
        JsbTileTrileTileCallMgr.handler("sensorsBuryPoint","(Ljava/lang/String;Ljava/lang/String;)V","startclick","")
      
    }
    //每个50秒恭喜获得受奖名单
    executeEvery50Seconds() {
        if (GameTileStaticData.isShenHeModel) {
            return
        }
        let isChangeParent = false;
        cc.director.getScheduler().schedule(() => {
            if(!isChangeParent)
            {
               
                isChangeParent = true;
                let canvas = cc.director.getScene().getChildByName("Canvas");


                const worldPos = this.winMoneyNode.parent.convertToWorldSpaceAR(this.winMoneyNode.position);
                this.winMoneyNode.removeFromParent(false);
                canvas.addChild(this.winMoneyNode);
                this.winMoneyNode.position = canvas.convertToNodeSpaceAR(worldPos);
            }
            this.winMoneyNode.getComponent("winMoneyPop").show();
         
            this.winMoneyNode.active = true;
        }, this, 50, cc.macro.REPEAT_FOREVER, 0, false);
    }
    public updateNewPhoneIcon ()
     {
        if(GameSceneController.I)
        {
            if(GameSceneController.I.NewPhoneNode)
            {
                
            if(ArchiveSystem.localData.lastOpenPhoneTaskId != ArchiveSystem.localData.curTaskId)
             {
                GameSceneController.I.NewPhoneNode.active = true;
             }
             else
             {
                GameSceneController.I.NewPhoneNode.active = false;
             }
            }
        }
       
     }
    public startGame() {
        GamingSystem.init();
        TopAreaTs.I.setLevel();
        this.cleanPlayArea();
        this.controleShenHeNode(!GameTileStaticData.isShenHeModel)

        ProgressController.I.init();
        ProgressPassNum.I.refresh()
        getEventEmiter().emit(wabaoEmit.wabao_refresh_left_time,{})
        //SceneManagerSystem.showLevelPanels(()=>{
            // if (GameStaticData.isShenHeModel) {
            //     GamePlayController.I.setMap(0,0); 
            // }else{
            //     GamePlayController.I.setMap(GameData.LevelData.coinTile,GameData.LevelData.moneyTile); 
            // }
            // ProgressController.I.refresh();
            // getEventEmiter().emit(CUSTOM_EVENT_NAME.onSceneChangedComplete,'setMap');
        //})
        this.scheduleOnce(()=>{
            if (GameTileStaticData.isShenHeModel) {
                GamePlayController.I.setMap(0,0); 
            }else{
                GamePlayController.I.setMap(GameData.LevelData.coinTile,GameData.LevelData.moneyTile); 
            }
            ProgressController.I.refresh();
            getEventEmiter().emit(CUSTOM_EVENT_NAME.onSceneChangedComplete,'setMap');
            GamePlayController.I.showMaps("setMap")
            if (GameData.LevelData.passNum == GameTileStaticJsonData.tixianParm.sl+1) {
                if (GameTileStaticJsonData.getLocalNormalByKey(LocalKey.localTiXianStartTip) == 0) {
                    this.guideToClickLibao()
                }
                
            }
        },1)
    }

    onGameStart(){
        // let isguid1 = GameData.LevelData.passNum == 1 && GameData.LevelData.novice == 0;
        // let isguid2 = GameData.LevelData.passNum == 2 && GameData.LevelData.novice2 == 0;
        let isguid1 = GameData.LevelData.passNum == 1 && (GameData.AccountData.moneytotal<=0);
        //let isguid2 = GameData.LevelData.passNum == 2 && (GameData.AccountData.cointotal<=0);
        let isguid2 = false
      
        if (GameTileStaticData.isShenHeModel) {
            //审核版本去掉新手引导
            isguid1 = false
            isguid2 = false
        }
        
        if (isguid1 || isguid2){
            this.UGuider1.active = true;
            this.UGuider1.off(cc.Node.EventType.TOUCH_END)
            let playerNode = this.UGuider1.getChildByName("playerNode");
            let mask = this.UGuider1.getChildByName("mask");
            let hand = this.UGuider1.getChildByName("hand");
            let blockhand = this.UGuider1.getChildByName("blockhand");
            let label_des = cc.find("player/talkbg/lab_des",playerNode).getComponent(cc.Label)
            hand.active = false;
            mask.setContentSize(0,0)
            let miny = Number.MAX_VALUE
            let same = []
            let clicknum = 0
            let clickitem = []
            let touchItem = ()=>{
                for(let i = 0 ;i <same.length;i++){
                    if (same[i].available && clickitem.indexOf(i) == -1){
                        blockhand.position = blockhand.parent.convertToNodeSpaceAR(same[i].node.convertToWorldSpaceAR(cc.Vec3.ZERO)).sub(cc.v3(-50,50))
                        blockhand.active = true
                        blockhand.zIndex = 100
                        break;
                    }
                    blockhand.active = false;
                }
            }
            let msgPack = {}
            if(isguid1){
                same = this.findSame();
                msgPack = {
                    rewardMoney:GameTileStaticJsonData.newUserAward.money,
                    type:"newplayerlibao"
                }
                label_des.string = LanguagetileTile.getWord("CTTTSITVTTDA")
            }else{
                same = this.findJinBiSame();
                msgPack = {
                    rewardCoin:GameTileStaticJsonData.newUserAward.coin,
                    type:"newplayerlibao"
                }
                label_des.string = LanguagetileTile.getWord("YCGAGRBETGC")
            }

            same.forEach((item,index)=>{
                let wpos = item.node.convertToWorldSpaceAR(cc.Vec3.ZERO);
                let lpos = this.UGuider1.convertToNodeSpaceAR(wpos);
                item.node.setParent(this.UGuider1); 
                item.node.position = lpos;
                miny = Math.min(lpos.y,miny);
                item.isClick = false;
                touchItem();
                item.touchEnd = ()=>{  
                    if(item.isClick == true)
                    {
                        return false;
                    }
                    item.isClick = true;
                    clickitem.push(index)
                    item.node.off(cc.Node.EventType.TOUCH_END,item.touchEnd)
                    item.collect();
                    touchItem();
                    clicknum ++
                    
                    if (isguid1) {
                        JsbTileTrileTileCallMgr.handler("sensorsBuryPoint","(Ljava/lang/String;Ljava/lang/String;)V","lv1_guide_"+clicknum,"")
                        let jsonStr = {event:"lv1_guide_"+clicknum,loglevel:2}
                        JsbTileTrileTileCallMgr.handler("buryPoint","(Ljava/lang/String;)V",JSON.stringify(jsonStr))
                    }else if(isguid2){
                        JsbTileTrileTileCallMgr.handler("sensorsBuryPoint","(Ljava/lang/String;Ljava/lang/String;)V","lv2_guide_"+clicknum,"")
                        
                        let jsonStr = {event:"lv2_guide_"+clicknum,loglevel:2}
                        JsbTileTrileTileCallMgr.handler("buryPoint","(Ljava/lang/String;)V",JSON.stringify(jsonStr))
                    }
                    if (clicknum  == BLOCK_ELIMINATE_LIMIT){
                        this.UGuider1.active = false;
                        let callback = async ()=>{
                            this.UGuider1.active = false;
                            let redtarget:cc.Node
                            if(isguid1){
                                redtarget = TopAreaTs.I.getRedbagFlyTarget();
                                label_des.string = LanguagetileTile.getWord("CHTWM")
                                GameData.LevelData.novice = 1;
                            }else if (isguid2){
                                redtarget = TopAreaTs.I.getCoinFlyTarget();
                                label_des.string = LanguagetileTile.getWord("YCUGTC")
                                GameData.LevelData.novice2 = 1;
                            }
                            mask.width = redtarget.width + 50;
                            mask.height = redtarget.height+10;
                            let lpos = mask.parent.convertToNodeSpaceAR(redtarget.convertToWorldSpaceAR(cc.Vec3.ZERO)).sub(cc.v3(5,5))
                            mask.position = lpos
                            hand.position = lpos.add(cc.v3(140,-100))
                            hand.active = true;
                            playerNode.y = lpos.y - playerNode.height
                            this.UGuider1.on(cc.Node.EventType.TOUCH_END,()=>{
                                this.onButtonClick({target:redtarget})
                                this.UGuider1.active = false;
                            })
                            //await GetAccountInfo();
                        }
                        if (isguid1){
                            SceneManagerSystem.showGetRedBagPanels("newplayerlibao",callback);
                        }else{
                            SceneManagerSystem.showGetCoinOrLiBaoPanels("newplayerlibao",0,callback,msgPack)
                        }
                    }
                    return true;
                }
                item.node.on(cc.Node.EventType.TOUCH_END,item.touchEnd)

             

            })
               // Assuming the parent node has a reference called parentNode
               this.node.on(cc.Node.EventType.TOUCH_END, function (event) {
                if (isguid1 || isguid2)
                {
                    let isTouchOut = true;
                    same.forEach((item,index)=>{

                        
                        if(event.target == item.node)
                        {
                            isTouchOut = false;
                        }
                    
                      
                    })
                    if(isTouchOut)
                    {
                        let isFind = false;
                        same.forEach((item,index)=>{

                            if(isFind == false)
                            {
                                if(item.touchEnd() == true)
                                {
                                    isFind = true;
                                }
                            }
                        })
                    }

                }
                
            }, this);

            playerNode.y = miny - playerNode.height/2 - 100

        }
       
    }
    //到了第10关引导点击提现
    guideToClickLibao(){
        if (GameTileStaticData.isShenHeModel) {
            return
        }
        ProgressPassNum.I.changeLiHeStatus()
        this.UGuiderToDraw.active = true;
        let mask = this.UGuiderToDraw.getChildByName("mask");
        let hand = this.UGuiderToDraw.getChildByName("hand");
        let nodeClick = this.UGuiderToDraw.getChildByName("nodeClick");
        
        let redtarget = ProgressPassNum.I.node
        mask.width = redtarget.width
        mask.height = redtarget.height
        nodeClick.width = redtarget.width
        nodeClick.height = redtarget.height
        
        let lpos = mask.parent.convertToNodeSpaceAR(redtarget.convertToWorldSpaceAR(cc.Vec3.ZERO)).sub(cc.v3(5,5))
        mask.position = lpos
        nodeClick.position = lpos
        hand.position = lpos.add(cc.v3(210,-120))
        hand.active = true;
        
        nodeClick.on(cc.Node.EventType.TOUCH_END,()=>{
            this.UGuiderToDraw.active = false;
            JsbTileTrileTileCallMgr.handler("sensorsBuryPoint","(Ljava/lang/String;Ljava/lang/String;)V","guidetixianclick","")
            let jsonStr = {event:"guidetixianclick",loglevel:2}
            JsbTileTrileTileCallMgr.handler("buryPoint","(Ljava/lang/String;)V",JSON.stringify(jsonStr))
            GameTileStaticJsonData.saveLocalNormalByKey(LocalKey.localTiXianStartTip,1)
            ProgressPassNum.I.onClickToDrawMoney()
        })
    }
    public findSame() {
        
        let blocks = GamePlayController.I.getBlocksAvailable();
        let checked: SingleBlockController[] = [];
        
        for (let i: number = 0; i < blocks.length; i++) {
            let o = blocks[i];
            if (checked.some((v: SingleBlockController) => { return v.blockSkin.spriteFrame == o.blockSkin.spriteFrame })) continue;
            checked.push(o);
            let same = blocks.filter((v: SingleBlockController) => { return v.blockSkin.spriteFrame == o.blockSkin.spriteFrame });
            if (same.length >= BLOCK_ELIMINATE_LIMIT) {
                return same.slice(0, BLOCK_ELIMINATE_LIMIT);
            }
        }
    }
    
    public findJinBiSame() {
       
        let blocks = GamePlayController.I.getBlocksAvailable();
        let checked: SingleBlockController[] = [];
        let same = []
        for (let i: number = 0; i < blocks.length; i++) {
            let o = blocks[i];
            if (GamePlayController.I.isJinBiBlock(o)){
                same.push(o);
                if (same.length >= BLOCK_ELIMINATE_LIMIT) {
                    return same.slice(0, BLOCK_ELIMINATE_LIMIT);
                }
            }
        }
    }

    onButtonClick(event,value = null){

      
        let passNumStr = GameData.LevelData.passNum+""

        let moneyNumStr = ""
        // let origin = GameMatchTileStaticJsonData.getTwoPointNum(GameData.AccountData.moneytotal*GameMatchTileStaticJsonData.getMoneyChangeRate) 
        // if (LanguageMatchTile.getCountry != Country.ID){
        //     moneyNumStr = origin+""
        // }else{
        //     moneyNumStr = Number(Math.floor(origin))+""
        // }
        moneyNumStr = GameData.AccountData.moneytotal+""
        let jsonStr = {passNum:passNumStr,
            coinNum:"0",
            moneyNum:moneyNumStr,
            moneyrate:GameTileStaticJsonData.getMoneyChangeRate+"",
            tixianstartlv:GameTileStaticJsonData.tixianParm.sl+"",
            needsignDays:GameTileStaticJsonData.tixianParm.r1+"",
            needvideo:GameTileStaticJsonData.tixianParm.r2+"",
            tixianshenlv:GameTileStaticJsonData.tixianParm.r3+""}
        
        if (event.target.name == "coinbg"){
            JsbTileTrileTileCallMgr.handler("coinDrawCash","(Ljava/lang/String;)V",JSON.stringify(jsonStr))
        }else if (event.target.name == "redbg"||event.target.name == "tipBtn"){
            JsbTileTrileTileCallMgr.handler("moneyDrawCash","(Ljava/lang/String;)V",JSON.stringify(jsonStr))
        }
        if(value == "phone")
        {
            JsbTileTrileTileCallMgr.handler("sensorsBuryPoint","(Ljava/lang/String;Ljava/lang/String;)V","iphoneClick","")
                        
            let jsonStr = {event:"iphoneClick",loglevel:2}
            JsbTileTrileTileCallMgr.handler("buryPoint","(Ljava/lang/String;)V",JSON.stringify(jsonStr))
            SceneManagerSystem.showPhonePanels();
        }
        else
        {
            CCLog.log("onButtonClick",event);
        }
    }

    /**
     * 美钞飞行动效
     */
    showMoneyFlyAnim(pos?: cc.Vec3, count?: number, parent?: cc.Node) {
        if (GameTileStaticData.isShenHeModel) {
            return
        }
        if (TopAreaTs.I) {
            let targetNode = TopAreaTs.I.getCoinFlyTarget();
            if (targetNode) {
                MoneyFlySky.popUpCustom(
                    pos ? pos : cc.v3(cc.view.getVisibleSize().width / 2, cc.view.getVisibleSize().height / 2),
                    targetNode.parent.convertToWorldSpaceAR(targetNode.position), targetNode, count,parent);
            }
        }
    }

    /**
     * 红包飞行动效
     */
    showRedbagFlyAnim(pos?: cc.Vec3, count?: number, parent?: cc.Node) {
        if (GameTileStaticData.isShenHeModel) {
            return
        }
        if (TopAreaTs.I) {
            let targetNode = TopAreaTs.I.getRedbagFlyTarget();
            if (targetNode) {
                RedbagFlySky.popUpCustom(
                    pos ? pos : cc.v3(cc.view.getVisibleSize().width / 2, cc.view.getVisibleSize().height / 2),
                    targetNode.parent.convertToWorldSpaceAR(targetNode.position), targetNode, count);
            }
        }
    }

    public cleanPlayArea(): void {
        // 清理地图
        GamePlayController.I.cleanMap();
        // 清理接收区
        CatcherController.I.clean();
    }

    public onPauseClick(): void {

        SceneManagerSystem.showSetPanel()
    }

    // 调试关卡用
    public async onNextClick() {
        await GamingSystem.loadMap(GamingSystem.mapInfo.level + 1);
        SceneManagerSystem.sceneChange(SCENES_NAME.GameScene);
    }

    protected onDestroy(): void {
        getEventEmiter().off(CUSTOM_EVENT_NAME.onGameStart,this.onGameStart.bind(this),this.node);
        getEventEmiter().off("updateNewPhoneIcon",this.updateNewPhoneIcon.bind(this),this.node);
        getEventEmiter().off("changeBg",this.changeBg.bind(this),this.node);
        
    }
}
